/*
 * CFileReader.cpp
 *
 *  Created on: 04.12.2012
 *      Author: caffeine
 */

#include "CFileReader.h"
#include <boost/filesystem.hpp>
#include <lampe/exception/IO.h>

namespace lampe{
namespace io{
u32 CFileReader::read(void* buffer, u32 size){
	return fread(buffer,1,size,pointer);
}
void CFileReader::position(u32 p){
	fseek(pointer,p,SEEK_SET);
}
u32 CFileReader::size(){
	s32 pos=ftell(pointer);
	fseek(pointer,0,SEEK_END);
	u32 ret=ftell(pointer);
	fseek(pointer,pos,SEEK_SET);
	return ret;
}
u32 CFileReader::position(){
	return ftell(pointer);
}

bool CFileReader::eof(){
	return feof(pointer);
}

CFileReader::CFileReader(boost::filesystem::path path) {
	pointer=fopen(path.string().c_str(),"rb");
	if (!pointer)
		GEN_IO_ERROR("File "+String(path.string().c_str())+" not found!");
}

CFileReader::~CFileReader() {
	fclose(pointer);
}

extern IFileReader*createFileReader(boost::filesystem::path fileName){
	if (!boost::filesystem::exists(boost::filesystem::path(fileName)))
		return 0;
	return new CFileReader(fileName);
}


extern String readTextFromFile(boost::filesystem::path fileName){
	IFileReader*file=createFileReader(fileName);
	if (!file)
		return "";
	//printf("Read file \"%s\"\n",fileName.c_str());
	//printf("File size %u",file->size());
	c8*data=new c8[file->size()+1];
	data[file->size()]=c8(0);
	file->read((void*)&data[0],file->size());
	String res(data);
	delete[]data;
	file->drop();
	return res;
}

}//namespace io
}//namespace lampe
